<template>
  <div class='container'>
    <el-dialog
      :title="this.subjectData.id ? '修改' : '添加'"
      :visible="addDialogVisible"
      @close="closeDialog"
      @open="openDialog"
    >
      <!-- 表单 -->
      <el-form
        ref="addForm"
        label-width="120px"
        :model="subjectData"
        :rules="rules"
      >
        <el-form-item label="学科名称" prop="subjectName">
          <el-input v-model="subjectData.subjectName" style="width: 50%" />
        </el-form-item>
        <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch
            v-model="subjectData.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value='1'
            :inactive-value='0'>
          </el-switch>
        </el-form-item>
      </el-form>
      <!-- footer插槽 -->
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects.js'
export default {
  name: 'SubjectsAdd',
  data () {
    return {
      subjectData: { subjectName: '', isFrontDisplay: 1 },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ],
        isFrontDisplay: [
          { required: true, trigger: 'blur' }
        ]
      }
    }
  },
  props: {
    addDialogVisible: {
      required: true
    },
    detail: {
      default: { subjectName: '', isFrontDisplay: 1 }
    }
  },
  methods: {
    confirm () {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          if (!this.subjectData.id) {
            // 新增
            await add(this.subjectData)
          } else {
            // 修改
            await update(this.subjectData)
          }
          // 提示：添加成功
          this.$message.success(this.subjectData.id ? '修改成功' : '添加成功')
          // 调用父组件的方法，渲染页面
          this.$parent.getSubjectList()
          // 通知父组件关对话框
          this.closeDialog()
        }
      })
    },
    cancel () {
      this.closeDialog()
    },
    openDialog () {
      this.subjectData = this.detail
    },
    closeDialog () {
      // 通知父组件，关闭对话框
      this.$emit('closeDialog')
      // 重置表单
      this.$refs.addForm.resetFields()
      this.subjectData = { subjectName: '', isFrontDisplay: 1 }
    }
  }
}
</script>

<style scoped lang='scss'></style>
